package com.maotai.app.thread;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import org.apache.http.client.config.RequestConfig;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.maotai.app.bean.MaotaiAppCookie;
import com.maotai.app.bean.MaotaiAppString;
import com.maotai.app.bean.Product741;
import com.maotai.app.service.MaotaiAppService;
import com.maotai.app.util.MaotaiAppHttpClientUtil;
import com.maotai.llzhou.bean.MaotaiWebCookie;
import com.maotai.llzhou.bean.ProductInfo;
import com.maotai.llzhou.util.FaceUtil;
import com.maotai.llzhou.util.HttpClientUtilNew;
import com.maotai.llzhou.util.IPFactory;

public class MaoTaiAppGrabSingleThread extends Thread {
	private MaotaiAppService maotaiAppService;
	private Map<String, Object> zhanghao;
	private String ipAndPort;
	
	public MaoTaiAppGrabSingleThread(MaotaiAppService maotaiAppService,
			Map<String, Object> zhanghao, String ipAndPort) {
		this.maotaiAppService = maotaiAppService;
		this.zhanghao = zhanghao;
		this.ipAndPort = ipAndPort;
	}

	public String getIpAndPort() {
		return ipAndPort;
	}

	public void setIpAndPort(String ipAndPort) {
		this.ipAndPort = ipAndPort;
	}

	public Map<String, Object> getZhanghao() {
		return zhanghao;
	}

	public void setZhanghao(Map<String, Object> zhanghao) {
		this.zhanghao = zhanghao;
	}

	public MaotaiAppService getMaotaiAppService() {
		return maotaiAppService;
	}

	public void setMaotaiAppService(MaotaiAppService maotaiAppService) {
		this.maotaiAppService = maotaiAppService;
	}

	@Override
	public void run() {
		try {
			MaotaiAppHttpClientUtil hcu = MaotaiAppHttpClientUtil.getInstance();
			// 先登录
			RequestConfig config = IPFactory.getKdRequestConfig(ipAndPort);
			
			Map<String, String> maps = new HashMap<String, String>();
			String acwTc = zhanghao.get("acwTc") + "";
			String auth = zhanghao.get("auth") + "";
			String memberid = zhanghao.get("memberid") + "";
			String invoiceId = zhanghao.get("invoiceId")+"";
			String addressId = zhanghao.get("addressId")+"";
			String provinceName = zhanghao.get("provinceName")+"";
			String latitude = zhanghao.get("latitude")+"";
			String longitude = zhanghao.get("longitude")+"";
			MaotaiAppCookie mc = new MaotaiAppCookie();
			mc.setAcwTc(acwTc);
			mc.setAuth(auth);
			mc.setMemberid(memberid);
			
			//查询登记状态，如果登记状态是待网点接单，那么直接返回
			//登记如果显示已经接单，那么也直接查询订单
			//不然查询订单
			//没有订单的话，直接再登记,或者没有人接单的话
			boolean hasQdOrder = false;
			boolean hasOrder = false;
			mc = hcu.sendHttpGetProxy(MaotaiAppString.QDORDERS_URL_NEW,
					mc, config, null);
			System.out.println(zhanghao.get("code")+"登记结果查询--- "+mc.getContent());
			//{"data":{"endRow":1,"firstPage":1,"hasNextPage":false,"hasPreviousPage":false,"isFirstPage":true,"isLastPage":true,"lastPage":1,"list":[{"createTime":"2018-07-06 21:46:40.0","goodsImage":"https://prod-oss.emaotai.cn/supplychain-dev/test/img/AY7bsN8ErQ.jpg","goodsName":"【茅台云商】贵州茅台酒 (新飞天) 53%vol 500ml（商品编号：741）","goodsNum":6,"id":384751,"itemId":"1179926380333332484","orderId":null,"orderStatus":3,"orderType":0,"skuId":"1179926380340672519"}],"navigatePages":8,"navigatepageNums":[1],"nextPage":0,"orderBy":null,"pageNum":1,"pageSize":10,"pages":1,"prePage":0,"size":1,"startRow":1,"total":1},"resultCode":0,"resultMsg":"success"}
			if(mc.getContent()!=null && !"".equals(mc.getContent())){
				//{"resultCode":401,"resultMsg":"no login","loginStatus":"1"}
				if(mc.getContent().contains("login")){
					zhanghao.put("loginstatus", "0");
					maotaiAppService.updateMaotaiAppLoginStatus(zhanghao);
					return;
				}
				
				JSONObject jObject2 = JSONObject.parseObject(mc
						.getContent());
				JSONObject data2 = jObject2.getJSONObject("data");
				JSONArray data3 = data2.getJSONArray("list");
				if (data3 == null || data3.size() == 0) {
					System.out.println(zhanghao.get("code")+" "+"账号没有登记--");
				}else{
					for (int i = 0; i < data3.size(); i++) {
						JSONObject temp = data3.getJSONObject(i);
						String orderNo = temp.getString("orderStatus");
						if("3".equals(orderNo)){
							//有登记过，但是网点还没有接单
							hasQdOrder = true;
							break;
						}else if("6".equals(orderNo)){
							//有登记过，但是没有网点接单
							continue;
						}else if("4".equals(orderNo)){
							//有登记过，网点接单
							//查询订单
							//已接单是4
							hasOrder = true;
						}else{
							hasOrder = true;
						}
					}
				}
			}
			
			if(hasOrder){
				//查询订单
				mc = hcu.sendHttpGetProxy(MaotaiAppString.ORDER_QUERY_URL_NEW,
						mc, config, null);
				System.out.println(zhanghao.get("code")+" "+mc.getContent());
				if(mc.getContent()!=null && !"".equals(mc.getContent())){
					JSONObject jObject2 = JSONObject.parseObject(mc
							.getContent());
					JSONObject data2 = jObject2.getJSONObject("data");
					JSONArray data3 = data2.getJSONArray("list");
					//看订单的状态，是不是未支付的
					if (data3 == null || data3.size() == 0) {
						System.out.println(zhanghao.get("code")+" "+"账号没有订单--");
					}else{
						for (int i = 0; i < data3.size(); i++) {
							JSONObject temp = data3.getJSONObject(i);
							JSONObject delivery = temp.getJSONObject("delivery");
							String address = delivery.getString("address");//"address": "江苏，无锡市，新区吼山南路591号龙记首饰",
							String deliveryMobile = delivery.getString("deliveryMobile");//"deliveryMobile": "13438822775",
							String deliveryName = delivery.getString("deliveryName");//"deliveryName": "朱根",
							String logisticsCompanyDesc = delivery.getString("logisticsCompanyDesc");//"logisticsCompanyDesc": "顺丰快递（贵）",
							String orderId = delivery.getString("orderId");//"orderId": 2265740,
							String waybillNo = delivery.getString("waybillNo");//"waybillNo": "620792631228"
							
							JSONObject orderMain = temp.getJSONObject("orderMain");
							String orderNo = orderMain.getString("orderNo");//"orderNo": "2018061501081",
							String orderTime = orderMain.getString("orderTime");//"orderTime": "2018-06-15 10:00:07",
							String payAmount = orderMain.getString("payAmount");//"payAmount": 7495.00,
							String payOnlineOff = orderMain.getString("payOnlineOff");//"payOnlineOff": "在线支付",
							String shopId = orderMain.getString("shopId");//"shopId": "1173773178264259584",
							String shopName = orderMain.getString("shopName");//"shopName": "茅台商城",
							String status = orderMain.getString("status");//"status": 5,
							String statusName = orderMain.getString("statusName");//"statusName": "已签收",
							zhanghao.put("address", address);
							zhanghao.put("deliveryMobile", deliveryMobile);
							zhanghao.put("deliveryName", deliveryName);
							zhanghao.put("kuaiditype", logisticsCompanyDesc);
							zhanghao.put("orderId", orderId);
							zhanghao.put("kuaidicode", waybillNo);
							zhanghao.put("orderNo", orderNo);
							zhanghao.put("orderTime", orderTime);
							zhanghao.put("payAmount", payAmount);
							zhanghao.put("payOnlineOff", payOnlineOff);
							zhanghao.put("shopId", shopId);
							zhanghao.put("shopName", shopName);
							zhanghao.put("status", status);
							zhanghao.put("statusName", statusName);
							//"statusName": "等待付款"
							if("1".equals(status)){
								hasOrder = true;
								maotaiAppService.insertMaotaiAppOrderItem(zhanghao);//"status": 1,
								break;
							}
						}
					}
				}
			}
			
			if(hasQdOrder){
				return;
			}
			if(!hasOrder){
				int mtBizId = 1;
				HttpClientUtilNew hcu2 = HttpClientUtilNew.getInstance();
				String code = zhanghao.get("code")+"";
				String token = zhanghao.get("token")+"";
				String name = zhanghao.get("name")+"";
				String zimId = "";
	            String bizId = "";
	            String certNumber = zhanghao.get("certNumber")+"";
	            MaotaiWebCookie mwc = new MaotaiWebCookie();
				mwc.setAuth(auth);
				//获得metainfo
		        JSONObject uploadJ = new JSONObject();
		        uploadJ.put("apdidToken",token+""+code) ;
		        uploadJ.put("appName","com.emaotai.ysapp") ;
		        uploadJ.put("appVersion",ProductInfo.PRODUCT_VERSION) ;
		        uploadJ.put("bioMetaInfo","3.3.0:98304,0") ;
		        uploadJ.put("deviceModel","M8"+code) ;
		        uploadJ.put("deviceType","android") ;
		        uploadJ.put("osVersion","6.0.1") ;
		        uploadJ.put("zimVer","1.0.0") ;
		        //System.out.println(uploadJ.toJSONString());
		        //将metainfo传到茅台服务端，得到 "zimId" : "e1570236d1cee15043f1823e202d628b",
		        Thread.sleep(100);
		        //采用最新的post
		        String initUrl = "https://i.cmaotai.com/huieryun-identity/api/v1/authant/faceverify/init";
		        String postData = "auditType=1&certNumber="+certNumber+"&metainfo="+URLEncoder.encode(uploadJ.toJSONString())+"&mtBizId="+mtBizId+"&userName="+URLEncoder.encode(name,"utf-8");
		        //String postData = "auditType=1&certNumber=320922198607240034&metainfo="+URLEncoder.encode(uploadJ.toJSONString())+"&mtBizId="+mtBizId+"&userName=%E5%91%A8%E4%BA%AE%E4%BA%AE";
		         for(int i=0;i<1;i++) {
		        	 mwc = hcu2.sendHttpPostAppProxy(initUrl, mwc, postData, config);
		            System.out.println(zhanghao.get("code")+"----初始化预约摄像头----" + mwc.getContent());
		            if (mwc.getContent().contains("繁忙")){
		            	zhanghao.put("yuyuestatus", "x");
		            	maotaiAppService.updateMaotaiAppYuYueStatus(zhanghao);
						 return;
		            }
		            if (mwc.getContent().contains("重试")||mwc.getContent().contains("抱歉")||mwc.getContent().contains("query")) {
		            	Thread.sleep(1000);
		                continue;
		            } else {
		                break;
		            }
		        }
		         if (mwc.getContent().contains("重试")){
		        	 //证明脸黑了
		        	 zhanghao.put("yuyuestatus", "x");
		        	 maotaiAppService.updateMaotaiAppYuYueStatus(zhanghao);
					 return;
		         }
		        if(mwc!=null && mwc.getContent()!=null){
		            JSONObject initJson = JSON.parseObject(mwc.getContent()).getJSONObject("data");
		            zimId = initJson.getString("zimId");
		            bizId = initJson.getString("bizId");
		            
		        }
		        //然后发起认证，认证完了回传到茅台服务器
	            //最后提交预约信息
		        if("".equals(zimId)||"".equals(bizId)) {
					zhanghao.put("yuyuestatus", "0");
					maotaiAppService.updateMaotaiAppYuYueStatus(zhanghao);
		        	return;
		        }
		        
		        boolean isFace = FaceUtil.faceToken(token,zimId,config,zhanghao);
		        if(!isFace){
		        	zhanghao.put("yuyuestatus", "7");
		        	maotaiAppService.updateMaotaiAppYuYueStatus(zhanghao);
		        	return;
		        }
		        Thread.sleep(3000);
		        initUrl = "https://i.cmaotai.com/huieryun-identity/api/v1/authant/faceverify/query?zimId="+zimId+"&bizId="+bizId+"&mtBizId="+mtBizId+"&auditType=1";
		        mwc = hcu2.sendHttpGetAppProxy(initUrl,mwc,config,null);
		        System.out.println(zhanghao.get("code")+"----识别结束提交服务器----"+mwc.getContent());
		        if(mwc.getContent().contains("身份")){
		        	zhanghao.put("yuyuestatus", "M");
		        	maotaiAppService.updateMaotaiAppYuYueStatus(zhanghao);
		        	return;
		        }
		        Thread.sleep(100);
		        //20180825茅台改为网页去验证，不在手机端提交查询
//		        String refererurl = "https://www.emaotai.cn/smartsales-b2c-web-pc/sign/signUp?info=eyJpdGVtTmFtZSI6IuOAkOiMheWPsOWVhuWfjumihOe6pui0reS5sOOAkei0teW3nuiMheWPsOmFku%2b8iOaWsOmjnuWkqe%2b8iTUzJXZvbCA1MDBtbO%2b8iOWVhuWTgee8luWPt%2b%2b8mjc0Me%2b8iSIsImltZ1VybCI6Imh0dHBzOi8vcHJvZC1vc3MuZW1hb3RhaS5jbi9zdXBwbHljaGFpbi1kZXYvdGVzdC9pbWcvQ3lma2RuUDVGcy5qcGciLCJza3VJZCI6IjExODA3MzE3OTk5MzE4MDg3NzEiLCJpdGVtSWQiOiIxMTgwNzMxNzk5OTI0NDY4NzQwIiwic2hvcElkIjoiMTE3Mzc3MzE3ODI2NDI1OTU4NCJ9";
//
//		        //https://i.emaotai.cn/huieryun-identity/api/v1/authant/faceverify/qrquery?mtBizId=2&appCode=1&_t=1535153490878
//		        initUrl = "https://i.emaotai.cn/huieryun-identity/api/v1/authant/faceverify/qrquery?mtBizId="+mtBizId+"&appCode=1";
//		        mwc = hcu2.sendHttpGetProxy(initUrl,mwc,config,refererurl);
//		        Thread.sleep(100);
//		        System.out.println(zhanghao.get("code")+"----查询识别结果----"+mwc.getContent());
//		        if(mwc!=null && !mwc.getContent().contains("success")){
//		            System.out.println("识别结果未成功");
////		            zhanghao.put("yuyuestatus", "M");
////					maotaiService.updateZhanghaoYuYueStatus(zhanghao);
////		            return;
//		            for(int i=0;i<5;i++){
//		            	mwc = hcu2.sendHttpGetProxy(initUrl,mwc,config,refererurl);
//		                System.out.println("maotaiAppCookie---"+mwc.getContent());
//		                if(mwc!=null && mwc.getContent().contains("success")){
//		                    break;
//		                }
//		            }
//		        }
				//表明没有订单,那么肯定是登记没有人接单,那么继续登记
				//先获取店铺的id
				//https://prod-www.emaotai.cn/yundt-application-trade-core/api/v1/yundt/trade/item/detail/get?itemId=1181477822877814793&province=广东省&lat=23.208041&lng=113.26775&memberId=985576
//				String skuIdUrl = "https://prod-www.emaotai.cn/yundt-application-trade-core/api/v1/yundt/trade/item/detail/get?itemId="+Product741.ITEMID+"&province="+URLEncoder.encode(provinceName)+"&lat="+latitude+"&lng="+longitude+"&memberId="+memberid;
//				mc = hcu.sendHttpGetProxy(skuIdUrl, mc, config, "");
//				
//				JSONObject sku = JSONObject.parseObject(mc.getContent());
//				String skuId = sku.getJSONObject("data").getString("skuId");
				//重新登记
				maps.clear();
				maps.put("addressId", addressId);
				maps.put("deliveryType", "3");
				maps.put("goodsNum", Product741.GOODSNUM);
//				maps.put("goodsNum", randomInt()+"");
				maps.put("invoiceId", invoiceId);
				maps.put("itemId", Product741.ITEMID);
				maps.put("orderType", "0");
				maps.put("remark", "");
//				maps.put("skuId", skuId);
				maps.put("skuId", Product741.SKUID);
				mc = hcu.sendHttpPostProxy(MaotaiAppString.SUBMITQDORDER_URL_NEW, mc, maps,config, null);
				//{"data":{"userInfo":{"code":null,"createPerson":"migration program","createTime":"2017-11-06 20:40:27","dr":0,"email":"&13372007847@email.email","hishopUserId":null,"id":985576,"lockStatus":null,"mobile":"13372007847","orderBy":null,"orderByDesc":null,"password":"54e5e348ef953214c3ca12209575c16c","passwordFormat":1,"remark":null,"salt":"","sqlFilters":null,"status":1,"tenantId":1,"updatePerson":"migration program","updateTime":"2018-06-27 07:01:41","userName":"13372007847","vshopUserId":1100490},"orderType":0,"address":{"accountId":985576,"address":"翠屏城,73栋805室","addressAlias":null,"areaCode":"0","cityCode":"320100000000","createPerson":"migration program","createTime":"2018-06-24 14:50:18","def1":null,"def10":null,"def11":null,"def12":null,"def13":null,"def14":null,"def15":null,"def16":null,"def17":null,"def18":null,"def19":null,"def2":null,"def20":null,"def21":null,"def22":null,"def23":null,"def24":null,"def25":null,"def3":null,"def4":null,"def5":null,"def6":null,"def7":null,"def8":null,"def9":null,"defaultStatus":1,"deliveryEmail":null,"deliveryMobile":"13372007847","deliveryName":"周亮亮","deliveryPhone":"13372007847","dr":0,"id":508033,"latitude":"31.79522","longitude":"118.857902","orderBy":null,"orderByDesc":null,"postcode":null,"provinceCode":"320000000000","sqlFilters":null,"streetCode":null,"tenantId":1,"updatePerson":"13372007847","updateTime":"2018-07-06 21:35:49"},"pname":"【茅台云商】贵州茅台酒 (新飞天) 53%vol 500ml（商品编号：741）","ip":"49.77.83.165","deliveryType":4,"remark":"","itemId":"1179926380333332484","addressDetail":"江苏省 南京市  翠屏城,73栋805室","cityName":"南京市","areaName":"","imageUrl":"https://prod-oss.emaotai.cn/supplychain-dev/test/img/AY7bsN8ErQ.jpg","provinceName":"江苏省","orderInvoice":{"accountId":985576,"bankAccount":"","contactAddress":null,"contactPerson":null,"contactPhone":null,"createPerson":"13372007847","createTime":"2018-07-06 21:40:32","def1":null,"def10":null,"def11":null,"def12":null,"def13":null,"def14":null,"def15":null,"def16":null,"def17":null,"def18":null,"def19":null,"def2":null,"def20":null,"def21":null,"def22":null,"def23":null,"def24":null,"def25":null,"def3":null,"def4":null,"def5":null,"def6":null,"def7":null,"def8":null,"def9":null,"dr":0,"id":"1180228871304401928","invoiceContent":"明细","invoiceContentType":1,"invoiceTaxType":1,"invoiceTitle":"周亮亮","invoiceTitleType":1,"invoiceType":2,"isDefault":1,"openBank":"","orderBy":null,"orderByDesc":null,"orgName":null,"registerAddress":"","registerPhone":"","sendType":null,"sqlFilters":null,"taxCode":"","tenantId":1,"updatePerson":"13372007847","updateTime":"2018-07-06 21:40:32"},"goodsNum":6,"skuId":"1179926380340672519","channelCode":"02"},"resultCode":0,"resultMsg":"success"}
				System.out.println(zhanghao.get("code")+"提交登记结果--- "+mc.getContent());
				if(mc.getContent().contains("失败")||mc.getContent().contains("503")){
					System.out.println(zhanghao.get("code")+" 登记失败");
					zhanghao.put("yuyuestatus", "0");
					zhanghao.put("isyuyue", "0");
					maotaiAppService.updateMaotaiAppYuYueStatus(zhanghao);
				}else{
					System.out.println(zhanghao.get("code")+" 登记成功");
				}
				Thread.sleep(10000);
				MaoTaiAppGrabSingleThread512 th512 = new MaoTaiAppGrabSingleThread512(maotaiAppService,zhanghao,ipAndPort);
				th512.start();
			}else{
				return;
			}
			
		} catch (Exception e) {
			zhanghao.put("yuyuestatus", "0");
			zhanghao.put("isyuyue", "0");
			try {
				maotaiAppService.updateMaotaiAppYuYueStatus(zhanghao);
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
//				e1.printStackTrace();
			}
//			e.printStackTrace();
		}
	}
	public static int randomInt(){
		int max = 5;
		int min = 2;
		Random random = new Random();
		int s1 = random.nextInt(max) % (max - min + 1) + min;
		return s1;
	}
}
